<!--
* description: 总部查看门店月销售计划&g=1
* author: wangml
* createdDate: 2020-12-01
-->

<template>
  <div class="app-container app-container-table">
    <!-- 单表格模版页面 -->
    <one-table-template
      ref="multipleTable"
      :dynamic-api-config="dynamicApiConfig"
      :dynamic-buttons="dynamicButtons"
      :dynamic-components="tableComponents"
      :dynamic-table-cols="dynamicTableCols"
      :dynamic-form-fields="formField"
      :dynamic-is-show-more-btn="true"
      :dynamic-is-show-select="true"
      :dynamic-api-style="apiStyle"
      :dynamic-page-size="15"
      :refresh-table-key="refreshTableKey"
      :callback-obj="callbackObj"
      @hiddenColData="hiddenColData"
    />
  </div>
</template>
<script>
import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import OneTableTemplate from '@/components/templates/oneTable'
import { exportExcel } from '@/utils/getTimeString'
import Vue from 'vue'
import api from '@/api/planReport'
import commData from '../common/index.js'

export default {
  name: 'HeadquarterViewStore',
  components: {
    OneTableTemplate
  },
  mixins: [oneTableWithViewTemplateMixins],
  // 阻塞路由预加载网格中组件的数据
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData(
      // 同时加载当前页面和编辑框页面的配置
      [to.path, ''],
      function() {
        next()
      })
  },
  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path
    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])
    return {
      curPopupsVisible: false,
      genCodeFiled: null,
      selectList: [],
      clickRowsData: {},
      popstate: 'add',
      showdia: false,
      // 指定请求类型 可以统一在 utils/config.js中配置
      apiStyle: 'restful',
      dynamicApiConfig: api.headquartersViewStorePlan,
      refreshTableKey: '0',
      ruleSettingShow: false,
      // table表格查询API配置对象
      // 动态组件-查询条件
      tableComponents:
          this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableComponents.length > 0
            ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableComponents
            : [
              ...commData.ModelOptions(2),
              {
                compKey: 'comKey6',
                labelName: '制定月份：',
                codeField: 'makingMonth',
                component: () => import('@/components/org/datePicker/datePicker.vue'),
                dateType: 'month',
                dateOptionsType: '3',
                // type: 'inputText',
                isMust: false,
                span: 6
              },
              {
                compKey: 'comKey7',
                labelName: '计划月份：',
                codeField: 'planMonth',
                component: () => import('@/components/org/datePicker/datePicker.vue'),
                dateType: 'month',
                // dateOptionsType: '3',
                parentFileds: 'disabled:FormulationMonth-PlanMonth--false',
                isMust: false,
                span: 6
              },
              {
                compKey: 'comKey9',
                labelName: '制作人：',
                codeField: 'creator',
                component: () => import('@/components/org/commonInput'),
                type: 'inputText',
                isMust: false,
                span: 6
              },
              {
                compKey: 'comKey11',
                labelName: '优先级别：',
                codeField: 'priorityLevel',
                lookuptype: 'VE1227',
                component: () => import('@/components/org/LookupValue'),
                type: 'dropdownList',
                isMust: false,
                isMul: true,
                span: 6
              },
              {
                compKey: 'comKey12',
                labelName: '门店名称：',
                codeField: 'dlrShortName',
                component: () => import('../components/multipleSearchInput'),
                type: 'inputText',
                dataToObject: {
                  // 控制弹窗页面 搜索 网格 元素
                  tableComponents: [
                    {
                      compKey: 'compKey1',
                      labelName: '门店编码：',
                      codeField: 'dlrCode',
                      component: () => import('@/components/org/commonInput'),
                      type: 'inputText',
                      isMust: true,
                      span: 8
                    },
                    {
                      compKey: 'compKey2',
                      labelName: '门店名称：',
                      codeField: 'dlrShortName',
                      component: () => import('@/components/org/commonInput'),
                      type: 'inputText',
                      isMust: true,
                      span: 8
                    }
                  ],
                  tableCols: [
                    {
                      prop: 'dlrCode',
                      label: '门店编码'
                    },
                    {
                      prop: 'dlrShortName',
                      label: '门店名称'
                    }
                  ],
                  formField: {
                    dlrShortName: '',
                    dlrCode: ''
                  },
                  returnField: {
                    prop: 'dlrShortName',
                    label: '门店名称'
                  },
                  api: api.dlrQuery
                },
                isMust: false,
                span: 6
              }
            ],
      formField: null,
      // 动态组件-按钮
      dynamicButtons: this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons.length > 0
        ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons
        : [
          {
            compKey: 'comKey1',
            type: 'primary',
            size: 'small',
            name: 'search',
            position: 'right',
            clickEvent: () => this.queryTable(),
            text: '查询'
          },
          {
            compKey: 'comKey0',
            type: '',
            size: 'small',
            name: 'reset',
            position: 'right',
            clickEvent: () => this.reset(),
            text: '重置'
          },
          {
            compKey: 'comKey2',
            type: '',
            size: 'small',
            name: 'export',
            position: 'left',
            clickEvent: () => this.export(),
            text: '导出'
          },
          {
            compKey: 'comKey3',
            type: '',
            size: 'small',
            disabled: true,
            name: 'confirm',
            position: 'left',
            clickEvent: () => this.save(this.selectList),
            text: '确认导入'
          }

        ],
      // 动态组件-表格网格列
      dynamicTableCols: this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableCols.length > 0
        ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableCols
        : [
          {
            prop: 'releaseId',
            label: '主键ID',
            hidden: true,
            alwaysHidden: true
          },
          {
            prop: 'updateControlId',
            label: '并发控制ID',
            hidden: true,
            alwaysHidden: true
          },
          {
            prop: 'planStatus',
            label: '计划状态'
          },
          {
            prop: 'makingMonth',
            label: '制定月份'
          },
          {
            prop: 'ttCode',
            label: '22位码'
          },
          {
            prop: 'planMonth',
            label: '计划月份'
          },
          {
            prop: 'planWeek',
            label: '计划周度'
          },
          {
            prop: 'planNum',
            label: '数量'
          },
          {
            prop: 'priorityLevel',
            label: '优先级别'
          },
          {
            prop: 'dlrCode',
            label: '门店编码'
          },
          {
            prop: 'dlrShortName',
            label: '门店名称'
          },
          {
            prop: 'carSeriesCode',
            label: '车系编码'
          },
          {
            prop: 'carSeriesCn',
            label: '车系名称'
          },
          {
            prop: 'carConfigCode',
            label: '基础车型编码'
          },
          {
            prop: 'carConfigCn',
            label: '基础车型名称'
          },
          {
            prop: 'optionalPagCode',
            label: '选装包编码'
          },
          {
            prop: 'optionalPagName',
            label: '选装包名称'
          },
          {
            prop: 'carColorCode',
            label: '车身颜色编码'
          },
          {
            prop: 'carColorName',
            label: '车身颜色名称'
          },
          {
            prop: 'carIncolorCode',
            label: '内饰颜色编码'
          },
          {
            prop: 'carIncolorName',
            label: '内饰颜色名称'
          },
          {
            prop: 'creator',
            label: '制作人'
          },
          {
            prop: 'createdDate',
            label: '制作时间'
          },
          {
            prop: 'submitTime',
            label: '提交时间'
          },
          {
            prop: 'empName',
            label: '审核人'
          },
          {
            prop: 'auditTime',
            label: '审核时间'
          }
        ],

      // 单表格模版页面组件回调事件
      callbackObj: {
        // 当选择项发生变化时会触发该事件（多选时）
        onCheckSelectChange: (selection) => {
          this.selectList[0] = selection.map(t => t.monthPlanId)
          this.selectList[1] = selection.map(t => t.updateControlId)
          this.handleSelectionChange(selection)
        }
      }
    }
  },
  created() {
    const viewPageCode = this.$route.path
    this.genCodeFiled = this.genUtil(this.tableComponents)
    const formField = this.genCodeFiled('codeField')
    this.formField = this.$utils.getFormField(this, formField, this.$ConfigCache.CacheConfig.cacheData[viewPageCode])
  },
  mounted() {
    // 列表查询
    this.queryTable(1)
  },
  methods: {
    // 确定导入
    save(val) {
      this.listLoading = true
      const returnObj = {
      // api配置
        ServiceCode: 'updateStoreMonthSalePlan',
        apiUrl: '/mp/e3sh/vesale/planreport/hpViewStorePlanService/updateStoreMonthSalePlan.do',
        variables: { monthPlanId: this.selectList[0], updateControlId: this.selectList[1] }
      }
      // 转换了中台请求格式数据
      var paramD = this.$getParams(returnObj, null, this.dynamicApiStyle)
      // 调用中台API方法（可复用）
      this.$requestAPI(paramD, this.dynamicApiStyle).then(response => {
        if (response.result === '0') {
          this.listLoading = false
          if (response.msg) {
            this.$message({ message: response.msg, type: 'warn', duration: 2000 })
          }
          return
        }
        this.listLoading = false
        // 返回json
        if (response.msg) {
          this.$message({ message: response.msg, type: 'warn', duration: 2000 })
        }
        this.queryTable()
        this.listLoading = false
      }).catch(err => {
        console.info(err)
        this.listLoading = false
      })
    },
    export() {
      if (this.selectList[0]) {
        this.formField.monthPlanId = this.selectList[0]
      }
      exportExcel(this.formField,
        api.exportStoreMonthSalePlan.APIUrl,
        'exportStoreMonthSalePlan', '总部查看门店月计划.xlsx')
    },
    // 自动生成codeField
    genUtil: (array) => (attr) => array.reduce((p, c) => { p[c[attr]] = ''; return p }, {}),
    // 保存 或新增 后会调用此方法
    popClose(type) {
      this.showdia = false
      if (type === 1) {
        this.queryTable(1)
      }
    },
    // 当选择项发生变化时会触发该事件
    handleSelectionChange(selection) {
      const btns = this.dynamicButtons.filter(o => o.disabled !== undefined)
      if (btns.length > 0) {
        const isCheck = selection && selection.length > 0
        btns.forEach((item) => {
          item.disabled = !isCheck
        })
      }
    },

    hiddenColData(data) {
      if (data && data.length > 0) {
        this.refreshTableKey += 1
        this.dynamicTableCols = data
      }
    }
  }
}
</script>

